package com.clannad.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.clannad.eduservice.Listener.SubjectExcelListener;
import com.clannad.eduservice.entity.EduSubject;
import com.clannad.eduservice.entity.excel.SubjectData;
import com.clannad.eduservice.entity.subject.OneSubject;
import com.clannad.eduservice.entity.subject.TwoSubject;
import com.clannad.eduservice.mapper.EduSubjectMapper;
import com.clannad.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author clannad
 * @since 2022-08-10
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try{
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查出一级分类
        LambdaQueryWrapper<EduSubject> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EduSubject::getParentId,0);
        List<EduSubject> oneSubjectList = this.list(lambdaQueryWrapper);
        //查出所有的二级分类
        LambdaQueryWrapper<EduSubject> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.ne(EduSubject::getParentId,0);
        List<EduSubject> twoSubjectList = this.list(lambdaQueryWrapper2);

        List<OneSubject> finalSubjectList=new ArrayList<>();
        for (int i = 0; i < oneSubjectList.size(); i++) {
            EduSubject eduSubject = oneSubjectList.get(i);
            OneSubject oneSubject=new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);
            List<TwoSubject> twoFinalSubject=new ArrayList<>();
            for (int i1 = 0; i1 < twoSubjectList.size(); i1++) {
                EduSubject eduSubject1 = twoSubjectList.get(i1);
                if (eduSubject1.getParentId().equals(oneSubject.getId())){
                    TwoSubject twoSubject=new TwoSubject();
                    BeanUtils.copyProperties(eduSubject1,twoSubject);
                    twoFinalSubject.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoFinalSubject);
            finalSubjectList.add(oneSubject);
        }
        return finalSubjectList;
    }
}
